package com.moli.iov.util;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.util.*;

public class ExcelUtil {

    /**
     * Logger for this class
     */
    private static final Logger logger = LoggerFactory.getLogger(ExcelUtil.class);

    /**
     * @param res
     * @param data
     * @param propNames
     * @param headStrs
     * @param title
     * @return
     * @throws Exception
     */
    public static void exportDataExcel(HttpServletRequest request, final HttpServletResponse res, final List data, final String[] propNames, final String[] headStrs, String title) throws Exception {
        res.reset();
        XSSFWorkbook book;
        try {
            book = new XSSFWorkbook();
            if (StringUtils.isBlank(title)) {
                title = "aaa";
            } else {
                title = title + DateUtil.format("yyyyMMddHHmmss", new Date());
            }
            XSSFSheet xs = book.createSheet(title);
            XSSFRow xr;
            XSSFCell xc;
            xr = xs.createRow(0);
            for (int i = 0; i < propNames.length; i++) {
                if (null == propNames[i] || "".equals(propNames[i])) {
                    continue;
                }
                xc = xr.createCell(i);
                xc.setCellValue(headStrs[i]);
            }
            final int dataEnd = data.size(), dataStart = 0;
            Field[] filed = new Field[0];
            //无数据的情况处理
            if (data != null && data.size() > 0) {
                filed = data.get(0).getClass().getDeclaredFields();
            }
            Map hm = new HashMap();

            for (Field f : filed) {
                hm.put(f.getName(), f.getName());
            }

            Object value = null;

            int excelStartRow = 1;
            for (int datarow = dataStart; datarow < dataEnd; excelStartRow++, datarow++) {
                final Object bean = data.get(datarow);
                xr = xs.createRow(excelStartRow);
                for (int col = 0; col < propNames.length; col++) {
                    xc = xr.createCell(col);
                    final String field = propNames[col];
                    if (null == field || "".equals(field)) {
                        continue;
                    }

                    if (hm.containsKey(field)) {
                        value = PropertyUtils.getSimpleProperty(bean, field);
                        if (value == null) {
                            value = " ";
                        }
                    } else value = "";

                    if (value instanceof Date) {
                        //xc.setCellValue(DateUtils.formatTime((Date)value));
                        String dateValue = DateUtil.format("yyyy-MM-dd HH:mm:ss", (Date) value);
                        xc.setCellValue(dateValue);
                    } else {
                        xc.setCellValue(value.toString());
                    }
                }
            }
            res.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            //处理导出时浏览器兼容问题
            boolean isMSIE = HttpUtil.isMSBrowser(request);
            if (isMSIE) {
                title = java.net.URLEncoder.encode(title, "UTF-8");
            } else {
                title = new String(title.getBytes("UTF-8"), "ISO-8859-1");
            }
            //response.setHeader("Content-disposition", "attachment;filename=\"" + fileName + "\"");
            res.setHeader("Content-disposition", "attachment;filename=" + title + ".xlsx");

            book.write(res.getOutputStream());

        } catch (final Exception e) {
            logger.error("导出Excel出错：{}", e);
            throw new Exception("导出Excel出错：" + e.getMessage(), e);
        }
    }

    /**
     * 返回字符串
     *
     * @param request
     * @param response
     */
    public static void returnStr(HttpServletRequest request, HttpServletResponse response, String json) {

        //放入需要返回的值
        //转为json

        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = null;
        try {
            out = response.getWriter();
            out.print(json);//返回json数值
        } catch (IOException e) {
            logger.error("返回json异常", e);
        } finally {
            out.flush();
            out.close();
        }
    }


//	private static void writeCell(String[] headers, List<List<String>> result, XSSFSheet sheet, List<XSSFRow> rowList) {
//		// 产生表格标题列
//		for (int i = 0; i < headers.length; i++) {
//			XSSFRow row = sheet.createRow(i);
//			XSSFCell cell = row.createCell((short) 0);
//			XSSFRichTextString text = new XSSFRichTextString(headers[i]);
//			cell.setCellValue(text.toString());
//			rowList.add(row);
//		}
//		// 遍历集合数据，产生数据列
//		if (result != null) {
//			int columnIndex = 1;
//			for (List<String> data : result) {
//				for (int i = 0; i < rowList.size(); i++) {
//					XSSFCell cell = rowList.get(i).createCell(columnIndex);
//					cell.setCellValue(data.get(i));
//				}
//				columnIndex++;
//			}
//		}
//	}


    private static void writeCell(String[] headers, List<List<String>> result, XSSFSheet sheet, List<XSSFRow> rowList) {
        // 产生表格标题列
        List<String> header = Arrays.asList(headers);
        List<List<String>> dataList = new ArrayList<>();
        dataList.add(header);
        if (result != null || result.size() > 0) {
            dataList.addAll(result);
        }

        for (int i = 0; i < dataList.size(); i++) {
            XSSFRow row = sheet.createRow(i);
            List<String> stringList = dataList.get(i);
            for (int j = 0; j < stringList.size(); j++) {
                XSSFCell cell = row.createCell((short) j);
                XSSFRichTextString text = new XSSFRichTextString(stringList.get(j));
                cell.setCellValue(text.toString());
            }
            rowList.add(row);
        }
    }

    public static File getExcelInputStream(String[] headers, List<List<String>> result, String fileName) throws Exception {
        XSSFWorkbook workbook = new XSSFWorkbook();
        // 生成一个表格
        XSSFSheet sheet = workbook.createSheet();
        List<XSSFRow> rowList = new ArrayList<>();
        writeCell(headers, result, sheet, rowList);
        File file = new File(fileName);
        OutputStream out = new FileOutputStream(file);
        try {
            workbook.write(out);
            out.flush();
            return file;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            out.close();
        }
        return null;
    }
}
